package com.kxxnzstdsw.utils

import cn.hutool.captcha.CaptchaUtil
import com.kxxnzstdsw.exception.ExceptionCode
import com.kxxnzstdsw.exception.can.ValidatorException
import io.lettuce.core.ExperimentalLettuceCoroutinesApi
import io.lettuce.core.SetArgs
import io.lettuce.core.api.StatefulRedisConnection
import io.lettuce.core.api.sync.multi
import java.io.OutputStream
import kotlin.time.DurationUnit
import kotlin.time.toDuration

fun getCaptchaKey(key: String) = "captcha-$key"

fun StatefulRedisConnection<String, String>.getCaptcha(key: String, with: Int, height: Int, out: OutputStream) {
  val captcha =
    CaptchaUtil.createGifCaptcha(with.takeIf { it <= 1000 } ?: 1000, height.takeIf { it <= 500 } ?: 500, 5)
  this.sync()
    .set(
      getCaptchaKey(key),
      captcha.code,
      SetArgs.Builder.ex(5.toDuration(DurationUnit.MINUTES).toLong(DurationUnit.SECONDS))
    )
  out.use {
    captcha.write(it)
  }
}

@OptIn(ExperimentalLettuceCoroutinesApi::class)
fun StatefulRedisConnection<String, String>.checkCaptcha(key: String, code: String) {
  this.sync().multi {
    val gKey = getCaptchaKey(key)
    if (get(gKey)?.lowercase() == code.lowercase()) {
      del(gKey)
    } else {
      throw ValidatorException(ExceptionCode.V_000002)
    }
  }
}

